#include "mainwindow.h"
#include "leoplusinunit.h"
#include <QApplication>
#include <QDir>
#include <QDebug>
#include <QPluginLoader>
#include <QDesignerCustomWidgetCollectionInterface>
#include <QIcon>
MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    this->setMaximumHeight(480);
    this->setMaximumWidth(800);
    this->resize(800,480);
    m_plugsinListWidget = new QListWidget(this);
    loadPlugin();

    this->setWindowTitle(QString("Leo 插件学习，共 %1 控件").arg(m_pluginsWidgets.count()));



}

MainWindow::~MainWindow()
{
}

bool MainWindow::loadPlugin()
{
    qDeleteAll(m_pluginsWidgets);
    m_pluginsWidgets.clear();
    m_plugsinListNames.clear();
    QDir pluginsDir(QApplication::applicationDirPath());

    pluginsDir.cd("plugins");

    foreach(QString fileName,pluginsDir.entryList(QDir::Files))
    {
        QString file = pluginsDir.absoluteFilePath(fileName);
        qDebug()<<fileName<<"   " << file << "\n";
        QPluginLoader pluginLoader(file);
        if(!pluginLoader.load())
        {
            return false;
        }
        QObject * plugin = pluginLoader.instance();
        if(plugin)
        {
            QString plugName = plugin->metaObject()->className();
            qDebug()<< "plugName= "<< plugName;
            QDesignerCustomWidgetCollectionInterface *interfaces = qobject_cast<QDesignerCustomWidgetCollectionInterface *>(plugin);
            if (interfaces)
            {
                m_pluginsWidgets = interfaces->customWidgets();
               //QList<QDesignerCustomWidgetInterface*>::const_iterator it=m_pluginsWidgets.begin();
               QListIterator<QDesignerCustomWidgetInterface*> it(m_pluginsWidgets);
                for(;it.hasNext();)
                {
                    QDesignerCustomWidgetInterface* w = it.next();
                    QIcon icon = w->icon();
                    QString name = w->name();
                    qDebug()<<"plugsin Name = "<<name;
                    QListWidgetItem * item = new QListWidgetItem(m_plugsinListWidget);
                    item->setText(name);
                    item->setIcon(icon);
                    m_plugsinListNames << name;
                }

                const QObjectList objList = plugin->children();
                foreach (QObject *obj, objList)
                {
                    QString className = obj->metaObject()->className();
                    qDebug()<<"new method get class Name = "<<className;
                }
            }

        }
        else
        {
            qDebug()<< "pluginLoader failed "<< "\n";
        }

    }
    return true;
}

